//
//  TopicDetailController.m
//  FbeeAPP
//
//  Created by dev-m on 2018/3/8.
//  Copyright © 2018年 mohao. All rights reserved.
//

#import "TopicDetailController.h"
#import "TopicDetailHeader.h"
#import "TopicObj.h"
#import "UIButton+BCYImage.h"

#import "TopicCommentCell.h"
#import "TopicCommentObj.h"

#import "CommentView.h"

@interface TopicDetailController ()<UITableViewDelegate,UITableViewDataSource>
{
    TopicObj *topicObj;
    NSMutableArray *listArray;
    
    UIView *navBar;
    UITableView *mainTable;
    TopicDetailHeader *header;
    
    CommentView *commentView;
    
}

@end

@implementation TopicDetailController

-(instancetype)initWithTopic:(TopicObj *)obj
{
    self = [super init];
    
    if (self) {
        topicObj = obj;
    }
    
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    listArray = [[NSMutableArray alloc] init];
    
    // 添加观察
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    self.titleLabel.text = NSLocalizedString(@"tNavBeeDetail", nil);
    self.largeTitle.hidden = YES;
    [self buildView];
    
    [self bringTitleToFront];
    [self.view bringSubviewToFront:navBar];
    
    [LoadingHelper showLoadingOnView:self.view];
    [self getCommentList];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


-(void)buildView
{
    navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, NavBarHeight)];
    navBar.backgroundColor = FBEE_COLOR_BACKGROUND;
    [self.view addSubview:navBar];
    
    UIButton *backNav =  [UIButton makeButton:^(TTButtonExtend *make) {
        make.setFrame(CGRectMake(0, StatusHeight, 60, 44));
        make.addImage([UIImage imageNamed:@"nav_back"],UIControlStateNormal);
        make.addTarget(self,@selector(navback));
        make.imageEdgeInsets = UIEdgeInsetsMake(13.5, 16, 13.5, 27);
        make.tag = 666;
        [navBar addSubview:make];
    }];
    
    UIButton *menu =  [UIButton makeButton:^(TTButtonExtend *make) {
        make.setFrame(CGRectMake(IPHONEWIDTH-44, StatusHeight, 44, 44));
        make.addImage([UIImage imageNamed:@"nav_share"],UIControlStateNormal);
        make.addTarget(self,@selector(onShare));
        [make setImageCenter];
        [navBar addSubview:make];
    }];
    
    header = [[TopicDetailHeader alloc] initWithObj:topicObj];
    mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, IPHONEHEIGHT) style:UITableViewStyleGrouped];
    mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    mainTable.alwaysBounceVertical = YES;
    mainTable.backgroundColor = [UIColor clearColor];
    mainTable.tableHeaderView =header;
    mainTable.delegate = self;
    mainTable.dataSource = self;
    [mainTable setContentInset:UIEdgeInsetsMake(NavBarHeight, 0, TabbarHeight+13, 0)];
    [mainTable setContentOffset:CGPointMake(0, -NavBarHeight)];
    [self.view addSubview:mainTable];
    
    __weak id sel = self;

    commentView = [[CommentView alloc] initWithReply:^(NSString *comment) {
        [sel sendComment:comment];
    }];
    commentView.bottom = IPHONEHEIGHT;
    [self.view addSubview:commentView];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self hideKeyboard];
}

#pragma - mark scrollView

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //导航渐变
    if (mainTable.top >= 0) {
        
        float alphaY = scrollView.contentOffset.y;
        
        float alpha = alphaY / (scrollView.bounds.size.height/5.0f);
        alpha = alpha<0?0:alpha;
        alpha = alpha>1?1:alpha;
        [self.navigationView setAlpha:alpha];
        [self.view bringSubviewToFront:self.navigationView];
        
        if (self.navigationView.alpha == 1) {
            navBar.hidden = YES;
        }
        else
        {
            navBar.hidden = NO;
        }
        
    }
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self hideKeyboard];
}

#pragma mark - TableView Cell

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return listArray.count;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TopicCommentObj *obj = [listArray objectAtIndex:indexPath.row];
    
    return obj.height;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellId = @"CELLID";
    
    TopicCommentObj *obj = [listArray objectAtIndex:indexPath.row];
    
    TopicCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (!cell) {
        cell = [[TopicCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.dataObj = obj;
    
    return cell;
}

#pragma mark - requst

-(void)getCommentList
{
    NSString *url = [NSString stringWithFormat:@"%@?tid=%@",TopicCommentList_URL,topicObj.topicId];
    [self get:url code:TopicCommentList_URL_Code];
}

-(void)sendComment:(NSString *)comment
{
    if ([NSString isEmptyString:comment]) {
        return;
    }
    
    if ([LoadingHelper isLoadingFromView:self.view]) {
        return;
    }
    
    [self post:TopicCreateCommentList_URL param:@{@"tid":topicObj.topicId,@"gid":topicObj.groupId,@"uid":[UserInfoManager sharedManager].userId,@"content":comment} code:TopicCreateCommentList_URL_Cdoe];
    
    [LoadingHelper showLoadingOnView:self.view];
    
}

#pragma mark - response

-(void)requestSuccess:(id)data code:(NSInteger)code
{
    
    if (code == TopicCommentList_URL_Code) {
        
        [LoadingHelper removeLoadingOnView:self.view];
        
        [EmptyViewHelper removeEmptyFromView:mainTable];

        [listArray removeAllObjects];
        
        NSArray *dataArray = [data objectForKey:@"commentList"];
        
        if (dataArray.count == 0) {
            
            if (listArray.count == 0) {
                UIView *emptyView = [EmptyViewHelper showEmptyOnView:mainTable imageName:@"common_empty" text:@"no data"];
                emptyView.height = 220;
                emptyView.top = header.height;
            }
            
        }
        
        for (NSDictionary *dataDict in dataArray)
        {
            TopicCommentObj *obj = [[TopicCommentObj alloc] init];
            [obj setObjByDict:dataDict];
            [listArray addObject:obj];
        }
        
        [mainTable reloadData];
    
    }
    
    //评论成功
    if (code == TopicCreateCommentList_URL_Cdoe) {
        [self getCommentList];
        [commentView clearText];
        
        topicObj.commentNum = [NSString stringWithFormat:@"%d",SafeGetIntValue(topicObj.commentNum)+1];
        [header refreshView];
        NSString *info = SafeGetStringValue([data objectForKey:@"msg"]);
        [NoticePopHelper showNoticeText:info];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_TopicCommentSuccess object:nil];
    }
    
}

-(void)requestLogicError:(id)data code:(NSInteger)code
{
    [super requestLogicError:data code:code];
    
    [LoadingHelper removeLoadingOnView:self.view];
}

-(void)requestFailure:(NSError *)error code:(NSInteger)code
{
    [LoadingHelper removeLoadingOnView:self.view];
}

#pragma mark - keyboard

-(void)hideKeyboard
{
    [commentView resignFirstResponder];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    
    [UIView animateWithDuration:[KeyBoardManager sharedManager].animationDuration animations:^{
        commentView.bottom = IPHONEHEIGHT - [KeyBoardManager sharedManager].keyHeight;
    }];
    
//    [UIView beginAnimations:nil context:nil];
//    
//    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    
    [UIView animateWithDuration:[KeyBoardManager sharedManager].animationDuration animations:^{
        commentView.bottom = IPHONEHEIGHT;
    }];
    
//    [UIView beginAnimations:nil context:nil];
//    commentView.bottom = IPHONEHEIGHT;
//    [UIView commitAnimations];
    
}

-(void)onShare
{
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Share object:nil];
}

@end
